/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities.adapters;

import java.util.ArrayList;
import java.util.List;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.util.TimetableHelper;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * A list adapter to show the list of {@link Course courses} from the online search.
 */
public class SearchResultAdapter extends ArrayAdapter<Course> {

	ArrayList<Course> _searchResults;
	
	public SearchResultAdapter(Context context, int textViewResourceId,
			List<Course> objects) {
		super(context, textViewResourceId, objects);
		if (objects!=null) {
			_searchResults=new ArrayList<Course>(objects);
		}
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder;
		if (convertView==null) {
			viewHolder=new ViewHolder();
			//inflate the item view by using the result layout
			convertView=LayoutInflater.from(getContext()).inflate(R.layout.result, null);
			viewHolder._txt1=(TextView) convertView.findViewById(R.id.text1);
			viewHolder._txt2=(TextView) convertView.findViewById(R.id.text2);
			convertView.setTag(viewHolder);
		}
		else {
			viewHolder=(ViewHolder) convertView.getTag();
		}
		Course c=getItem(position);
		if (c != null) {
			viewHolder._txt1.setText(c.get_courseCode() + " " + c.get_section());
			StringBuilder sBuilder = new StringBuilder();
			if (c.get_day()>0) {
				sBuilder.append(TimetableHelper.getWeekdayString(c.get_day() + 1)).append(", ");
			}
			if (c.get_startTime() >0&& c.get_endTime()>0) {
				sBuilder.append(TimetableHelper.getFormattedString(
						c.get_startTime(), TimetableHelper.TYPE_TIME))
				.append(" - ")
				.append(TimetableHelper.getFormattedString(c.get_endTime(),
						TimetableHelper.TYPE_TIME));
			}else {
				sBuilder.append("Time Not Available");
			}
			sBuilder.append(" @ ").append(!TextUtils.isEmpty(c.get_location())?c.get_location():"N/A");
			viewHolder._txt2.setText(sBuilder.toString());
		}
		return convertView; 
	}
	
	private static class ViewHolder{
		TextView _txt1;
		TextView _txt2;
	}

}
